﻿using Newtonsoft.Json.Linq;

namespace Newtonsoft.Json
{
    /// <summary>Utc时间转换成本地时间</summary>
    public class DateTimeUtcToLocalConverter : JsonConverter<DateTime>
    {
        public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var jt = JToken.ReadFrom(reader);
            return jt.Value<DateTime>();
        }

        public override void WriteJson(JsonWriter writer, DateTime utcTime, JsonSerializer serializer)
        {
            var localTime = TimeZoneInfo.Local; //本地时区时间

            serializer.Serialize(writer, utcTime != default ? TimeZoneInfo.ConvertTimeFromUtc(utcTime, localTime) : null);
        }
    }
}
